#!/usr/bin/env node

import {Command} from 'commander';
import chalk from 'chalk';
import path from 'path';
import {startServer} from './server/Server';
import {generateReport} from './reporter/reporter';
import {defaultConfig, globalConfig} from './config';
import {ProjectScanner} from './scanner';
import packageJson from '../package.json';

const program = new Command();

// 设置版本和描述
program
  .version(packageJson.version)
  .description(packageJson.description);

// 定义命令行选项
program
  .option('-p, --port <port>', '指定服务器端口', defaultConfig.server.port.toString())
  .option('-d, --depth <depth>', '指定扫描深度', defaultConfig.scan.depth.toString())
  .option('-o, --output <path>', '扫描结果输出文件路径（不启动服务器）')
  .option('-t, --target <path>', '要扫描的目标目录', '.')
  .option('-e, --exclude <dirs>', '要排除的目录，用逗号分隔');

program.parse(process.argv);

const options = program.opts();

// 主函数
async function main() {
  try {
    console.log(chalk.blue('dep-vista') + chalk.green(' - 项目依赖扫描工具'));
    const config = globalConfig.config;

    if (options.target) {
      config.scan.targetDir = path.resolve(options.target);
    }
    if (options.port) {
      config.server.port = parseInt(options.port, 10);
    }
    if (options.depth) {
      config.scan.depth = parseInt(options.depth, 10);
    }
    if (options.exclude) {
      config.scan.excludes = options.exclude.split(',').map((dir: string) => dir.trim());
    }

    console.log(chalk.yellow('扫描目标:'), config.scan.targetDir);
    console.log(chalk.yellow('扫描深度:'), config.scan.depth);
    console.log(chalk.yellow('排除目录:'), config.scan.excludes.join(', '));

    // 输出到文件或启动服务器
    if (options.output) {
      // 扫描项目
      const scanResults = await ProjectScanner.scanProject(config.scan.targetDir, {
        depth: config.scan.depth,
        excludes: config.scan.excludes,
        projectTypes: config.scan.projectTypes
      });
      const outputPath = path.resolve(options.output);
      await generateReport(scanResults, outputPath);
      console.log(chalk.green(`已生成扫描报告: ${outputPath}`));
    } else {
      startServer();
    }
  } catch (error) {
    console.error(chalk.red('错误:'), error);
    process.exit(1);
  }
}

main();

